<template>
  <div id="categoriesManagePage">
    <a-flex justify="space-between">
      <h2>分类管理</h2>
      <a-space>
        <a-button type="primary" @click="addCategory">+ 创建分类</a-button>
        <a-input v-show="addRef" v-model:value="newCategoryName"  placeholder="分类名称" />
        <a-button v-if="addRef" @click="doAddCategory">确定</a-button>
      </a-space>
    </a-flex>
    <div style="margin-bottom: 16px" />
    <!-- 搜索表单 -->
    <a-form layout="inline" :model="searchParams" @finish="doSearch">
      <a-form-item label="分类名称">
        <a-input v-model:value="searchParams.categoryName" placeholder="请输入分类名称" allow-clear />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit">搜索</a-button>
      </a-form-item>
    </a-form>
    <div style="margin-bottom: 16px" />
    <!-- 表格 -->
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <a-space wrap>
            <a-button danger @click="doDelete(record.categoryId)">删除</a-button>
          </a-space>
        </template>
        <template v-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-if="column.dataIndex === 'updateTime'">
          {{ dayjs(record.editTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
      </template>
    </a-table>
  </div>
</template>
<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import {
  addCategoriesUsingPost,
  deleteCategoryUsingPost,
  listCategoriesByPageUsingPost
} from '@/api/categoriesController.ts'
import dayjs from 'dayjs'

const columns = [
  {
    title: 'id',
    dataIndex: 'categoryId',
    width: 80,
  },
  {
    title: '分类名称',
    dataIndex: 'categoryName',
  },
  {
    title: '浏览次数',
    dataIndex: 'usageCount',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
  },
  {
    title: '操作',
    key: 'action',
  },
]

// 定义数据
const dataList = ref<API.Space[]>([])
const total = ref(0)

// 搜索条件
const searchParams = reactive<API.CategoriesQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'descend',
})

// 获取数据
const fetchData = async () => {
  const res = await listCategoriesByPageUsingPost({
    ...searchParams,
  })
  if (res.data.code === 0 && res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
}

// 页面加载时获取数据，请求一次
onMounted(() => {
  fetchData()
})

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.current,
    pageSize: searchParams.pageSize,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total) => `共 ${total} 条`,
  }
})

// 表格变化之后，重新获取数据
const doTableChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

// 搜索数据
const doSearch = () => {
  // 重置页码
  searchParams.current = 1
  fetchData()
}

// 删除数据
const doDelete = async (id: API.DeleteRequest) => {
  if (!id) {
    return
  }

  const res = await deleteCategoryUsingPost({ id })
  if (res.data.code === 0) {
    message.success('删除成功')
    // 刷新数据
    fetchData()
  } else {
    message.error('删除失败')
  }
}

const addRef = ref<boolean>(false)
const addCategory = () => {
  addRef.value = !addRef.value;
}

const newCategoryName = ref<string>('')

const doAddCategory = async () => {
  if (!newCategoryName) {
    return
  }
  const res = await addCategoriesUsingPost({ categoryName: newCategoryName.value })
  if (res.data.code === 0) {
    message.success('创建成功')
    // 刷新数据
    fetchData()
  } else {
    message.error('创建失败')
  }
}
</script>
